import { LayerConfig, addLayer, LayerType, removeLayer } from "../layer/layerManage.ts";
import { getLayerManagerState } from "../layer/layerManagerState.ts";
// 添加点图层
const addPointLayer = (map: mapboxgl.Map, sourceId: string, layerId: string, imageName: string, geojsonData: any) => {
    const source = {
        type: LayerType.geojson,
        data: geojsonData
    }
    const layer: LayerConfig = {
        id: layerId,
        type: LayerType.Symbol,
        source: source,
        layout: {
            'icon-image': imageName,
            'icon-size': 0.3,
            'text-field': '{label}',
            'text-offset': [0, 1.5],
            'text-anchor': 'top',
            'text-size': 14, // 设置文字大小
            'text-font': ['DIN Pro Medium', 'Arial Unicode MS Bold'], // 设置字体
        },
        paint: {
            'text-color': '#fff',
            'icon-color': "#ff0000",
            'text-halo-color': '#FFFFFF',// 添加文字描边
            'text-halo-width': 0.5 // 设置描边宽度
        }
    }
    map.addSource(sourceId, source);

    addLayer(getLayerManagerState(map), layer)
};

// 添加点击事件
const addClickEvent = (map: mapboxgl.Map, layerId: string, callback: (features: mapboxgl.MapboxGeoJSONFeature[]) => void) => {
    map.on('click', layerId, (e) => {
        callback(e.features || []);
    });
    map.on('mouseenter', layerId, () => {
        map.getCanvas().style.cursor = 'pointer';
    });
    map.on('mouseleave', layerId, () => {
        map.getCanvas().style.cursor = '';
    });
};

// 删除地图资源
const removeMapResources = (map: mapboxgl.Map, id: string) => {
    const layerId = id + '-layer';

    removeLayer(getLayerManagerState(map), layerId)

    map.off('click', layerId);
    map.off('mouseenter', layerId);
    map.off('mouseleave', layerId);
};

// 主函数，完成添加多个点、图片、事件等操作
const setupPointsOnMap = async (
    map: mapboxgl.Map,
    id: string,
    imageName: string,
    imageUrl: string,
    geojsonData: any,
    callback: (data: any) => void
): Promise<{ remove: () => void }> => {

    const sourceId = id + '-source';
    const layerId = id + '-layer';
    addPointLayer(map, sourceId, layerId, imageName, geojsonData);

    addClickEvent(map, layerId, (features) => {
        console.log('Clicked features:', features);
        features.forEach((feature) => {
            if (callback) callback(feature.properties);
            console.log('Properties of clicked feature:', feature.properties);
        });
    });

    return {
        remove: () => {
            removeMapResources(map, id);
        }
    };
};

export { setupPointsOnMap, removeMapResources }
